import WayBaseControl from "./WayBaseControl";

const { ccclass, property } = cc._decorator;

@ccclass
export default class boxControl extends cc.Component {
    @property
    friction: number = 0.3;//碰撞体摩擦力系数[0~1]
    @property
    restitution: number = 0.4;//碰撞体的弹性系数[0~1]
    @property
    offsetUp: number = 15;
    @property
    offsetDown: number = 10;
    wayNode: cc.Node = null;
    wayCheckA: boolean = false;
    wayCheckB: boolean = false;
    _EnterWay: cc.Node = null;
    onLoad() {
        let collider = this.node.getComponent(cc.PhysicsBoxCollider);
        collider.friction = this.friction;
        collider.restitution = this.restitution;
        let nodeSize = this.node.getContentSize();
        nodeSize.height = nodeSize.height - this.offsetUp - this.offsetDown;
        nodeSize.width -= 10;
        collider.size = nodeSize;
        collider.offset.y = (this.offsetDown - this.offsetUp) / 2;
        collider.tag = TagBox;

        let areadown = this.node.addComponent(cc.BoxCollider);
        areadown.tag = TagBox;
        let sizedown = this.node.getContentSize();
        areadown.size = new cc.Size(sizedown.width + 4, sizedown.height - this.offsetUp);
        areadown.offset.y -= this.offsetUp / 2;

        let areaup = this.node.addComponent(cc.BoxCollider);
        areaup.tag = TagWayTrack;
        let size = this.node.getContentSize();
        areaup.size = new cc.Size(size.width - 4, this.offsetUp);
        areaup.offset.y = + (sizedown.height - this.offsetUp) / 2;
    }
    onCollisionEnter(other, self) {
        if (other.tag == TagWayBody1 || other.tag == TagWayBody2 ) {
            if (other.node.uuid != this.wayNode.uuid) {
                this.wayCheckA = true;
                this._EnterWay = other.node;
                if (this.wayCheckB) {
                    this.wayCheckB = false;
                    this.wayCheckA = false;
                    this.newWayNode(other.node);
                }
            }
        }
    }
    onCollisionExit(other, self) {
        if (other.tag == TagWayBody1 || other.tag == TagWayBody2 ) {
            if (other.node.uuid == this.wayNode.uuid) {
                this.wayCheckB = true;
                if (this.wayCheckA) {
                    this.wayCheckA = false;
                    this.wayCheckB = false;
                    this.newWayNode(this._EnterWay);
                }
            }
        }
    }
    newWayNode(newWay: cc.Node) {
        let way1 = this.wayNode.getComponent(WayBaseControl);
        way1.removeBoxOccupy(this.wayNode.uuid);
        let way2 = newWay.getComponent(WayBaseControl);
        way2.addBoxOccupy(newWay.uuid);
        this.wayNode = newWay;
    }
}
